<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>

<body>
    <script>
        function _ajaxTool(method, url, data) {
            return new Promise(function(resolve, reject) {
                let xhr = new XMLHttpRequest();
                if (method == "GET") {
                    //对data进行处理=>生成新的url
                    let a = "";
                    for (let key in data) {
                        a += `${key}=${data[key]}&`;
                    }
                    let newUrl = `${url}?${a.slice(0, -1)}`;
                    xhr.open(method, newUrl);
                    xhr.send();
                } else {
                    let postData = "";
                    xhr.open(method, url);
                    xhr.setRequestHeader(
                        "Content-type",
                        "application/x-www-form-urlencoded"
                    );
                    for (let key in data) {
                        postData += `${key}=${data[key]}&`;
                    }
                    postData = postData.slice(0, -1);
                    xhr.send(postData);
                }
                xhr.addEventListener("readystatechange", function() {
                    if (xhr.readyState == 4) {
                        if (xhr.status == 200) {
                            resolve(JSON.parse(xhr.responseText));
                        } else {
                            reject("请求有问题，请检查参数或者地址是否正确");
                        }
                    }
                });
            });
        }
        let url = "http://netease.0melon0.cn/search";
        let data = {
            keywords: "薛之谦",
            limit: 20,
            offset: 0,
        };
        //   _ajaxTool("GET", url, data, (res) => {
        //     console.log(res);
        //   });

        // _ajaxTool("GET", url, data)
        //     .then((res) => {
        //         console.log(res);
        //     })
        //     .catch((err) => {
        //         console.log(err);
        //     });

        async function log() {
            let res = await _ajaxTool('GET', url, data);
            console.log(res);
        }

        log()
    </script>
</body>

</html>